import os
from os import environ
import captcha
import logging
import datetime
import urllib
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
from google.appengine.ext import db
from google.appengine.api import images
import re

PAGESIZE = 10

class Greeting(db.Model):
  image = db.BlobProperty()
  date = db.DateTimeProperty(auto_now_add=True)


class Log(db.Model):
  comment = db.StringProperty()
  name =  db.StringProperty()
  category = db.IntegerProperty(default=0)
  scategory = db.StringProperty()
  scolor = db.StringProperty()
  pinlabel =  db.StringProperty()
  when =  db.StringProperty()
  created = db.DateTimeProperty(auto_now_add=True)
  #index = db.IntegerProperty(default=1)
  #ID = db.IntegerProperty(default=1)
  imageindex = db.IntegerProperty(default=0)
  deleteRequested = db.BooleanProperty(default=False)
  image = db.BlobProperty(default='')

class Group(db.Model):
    date = db.DateTimeProperty(auto_now_add=True)
    center_lat = db.FloatProperty()
    center_lng = db.FloatProperty()
    marker_lat = db.FloatProperty()
    marker_lng = db.FloatProperty()
    zoom = db.IntegerProperty(default=2)
    place = db.StringProperty()
    people = db.StringProperty('neighbors')
    contact =  db.StringProperty()
    moreinfo =  db.StringProperty()
    moreinfoLog =  db.StringProperty(default='')
    moreinfoImage =  db.StringProperty(default='')
    activity =  db.StringProperty(default='live')
    activityLog =  db.StringProperty(default='know')
    user = db.UserProperty()
    mapdefined = db.BooleanProperty(default=False)
    countLog = db.IntegerProperty(default=0) 
    imageLog = db.IntegerProperty(default=0)
    category = db.StringListProperty(default=["typical special"])
    categoryLog = db.StringListProperty(default=["typical special"])
    categoryImage = db.StringListProperty(default=["typical special"])
    color = db.StringListProperty(default=["ff0000 ffff00"])
    colorLog = db.StringListProperty(default=["ff0000 ffff00"])
    colorImage = db.StringListProperty(default=["ff0000 ffff00"])
    pagesizeLog = db.IntegerProperty(default=10)
    geoboxes = db.StringListProperty()
    prevgroup =  db.StringProperty(default='')
    nextgroup =  db.StringProperty(default='')
    acrossgroup =  db.StringProperty(default='')
    pintext =  db.StringProperty(default='Name')
    
class Pin(db.Model):
    date = db.DateTimeProperty(auto_now_add=True)
    lat = db.FloatProperty()
    lng = db.FloatProperty()
    name = db.StringProperty()
    cornerColor	 = db.StringProperty(default='ffffff')
    height = db.IntegerProperty(default=32)
    label = db.StringProperty(default='')
    labelColor = db.StringProperty(default='000000')
    labelSize = db.IntegerProperty(default=2)
    primaryColor = db.StringProperty(default='ff0000')
    shadowColor = db.StringProperty(default='000000')
    shape = db.StringProperty(default='circle')
    strokeColor = db.StringProperty(default='000000')
    width = db.IntegerProperty(default=32)
    category = db.IntegerProperty(default=0)
    scategory = db.StringProperty()
    logindex = db.IntegerProperty(default=0)
    imageindex = db.IntegerProperty(default=0)
    deleteRequested = db.BooleanProperty(default=False)

# copy_properties is thanks to Alexander Kojevnikov 
def copy_properties(src, dst): 
    for name in src.properties(): 
        value = getattr(src, name) 
        setattr(dst, name, value) 

class MainPage(webapp.RequestHandler):
    def get(self):
        place_id = self.request.get("place", None)
        user = users.get_current_user()
        groups = db.GqlQuery("SELECT * FROM Group WHERE acrossgroup != '' ORDER BY acrossgroup , countLog DESC  LIMIT 500") 
        pattern = "I\d\d*"
        compiledPattern = re.compile(pattern)

        interstates = {}
        for group in groups:
            logging.info('group in groups:place %s,count %s' % (group.place,group.countLog))
            index = compiledPattern.search(group.place).group()
            interstates[index] = group.place

        interstateList = []
        for interstate in interstates:
            logging.info("place %s " % interstates[interstate])
            interstateList.append(interstates[interstate])

        if place_id is None: #no place has been set by the user
            path = os.path.join(os.path.dirname(__file__), 'choose_place.html')
            if user: #offer user or nonuser options back at choose.html
                url = users.create_logout_url(self.request.uri)
                url_linktext = 'Signout'
                url_linktextmore = ' if you wish. You will be returned to this page after you signout.'
            else:
                url = users.create_login_url(self.request.uri)
                url_linktext = 'Signin'
                url_linktextmore = ' if you will be creating a map for your group. You will be returned to this page after you signin.'
            template_values = {
                'url': url,
                'url_linktext': url_linktext,
                'url_linktextmore': url_linktextmore,
                'interstateList': interstateList,
                }
            self.response.out.write(template.render(path, template_values))
        else: #some place has been set by the person (may be user)
            #so pull up information on the place set by the person
            key = db.Key.from_path("Group", place_id)
            place = Group.get(key)
            #determine if place exists already
            #because choose_place.html has produced a desired place name
            #or because user has supplied a place name with ?...
            if place: #person's place DOES exist already
                maptemplate_values = dict(place_id=place.key(), place=place.place, 
                    people=place.people, center_lat=place.center_lat, 
                    center_lng=place.center_lng, map_zoom=place.zoom,
                    marker_lat=place.marker_lat, marker_lng=place.marker_lng, 
                    contact=place.contact, moreinfo=place.moreinfo,
                    prevgroup=place.prevgroup, nextgroup=place.nextgroup,
                    acrossgroup=place.acrossgroup, pintext=place.pintext,
                    category=place.category, color=place.color,
                    mapdefined=place.mapdefined,
                    countLog=place.countLog,
                    activity=place.activity, user=place.user)
                if place.mapdefined: #person's place exists as a map
                    if user and user == place.user: #user is owner and may revise the existing map
                        template_values = maptemplate_values
                        path = os.path.join(os.path.dirname(__file__), 'add_map.html')
                        self.response.out.write(template.render(path, template_values))
                    else: #is not a user so may only view the existing map
                        template_values = maptemplate_values
                        path = os.path.join(os.path.dirname(__file__), 'map.html')
                        self.response.out.write(template.render(path, template_values))
                else: #person's place does NOT exist as a map
                    if user: #user needs to create the map but log exists
                        place.center_lat = None
                        place.center_lng = None
                        place.zoom = None
                        place.marker_lat = None
                        place.marker_lng = None
                        if 0 < place.countLog :
                            place.activity = place.activityLog
                            place.moreinfo = place.moreinfoLog
                            place.color = place.colorLog
                            place.category = place.categoryLog
                        else:
                            place.people = ""
                            place.contact = ""
                            place.activity = ""
                            place.moreinfo = ""
                            place.prevgroup = ""
                            place.nextgroup = ""
                            place.acrossgroup = ""
                            place.pintext = ""
                        place.mapdefined = True
                        place.put()
                        pin = Pin(key_name=place_id)
                        pin.name = place_id
                        pin.put()
                        template_values = dict(place_id=place.key(), place=place.place, 
                            people=place.people, center_lat=place.center_lat, 
                            center_lng=place.center_lng, map_zoom=place.zoom,
                            marker_lat=place.marker_lat, marker_lng=place.marker_lng, 
                            contact=place.contact, moreinfo=place.moreinfo,
                            category=place.category, color=place.color,
                            prevgroup=place.prevgroup, nextgroup=place.nextgroup,
                            acrossgroup=place.acrossgroup, pintext=place.pintext,
                            mapdefined=place.mapdefined,
                            countLog=place.countLog,
                            activity=place.activity, user=place.user)
                        path = os.path.join(os.path.dirname(__file__), 'add_map.html')
                        self.response.out.write(template.render(path, template_values))
                    else: #send this person to the log for this group
                        self.redirect("/comment?place=%s" % place.place)
            else: #person's place does NOT exist in datastore
                if user: #user needs to create the map
                    place= Group(key_name=place_id)
                    place.place = place_id
                    place.user = user
                    place.center_lat = None
                    place.center_lng = None
                    place.zoom = None
                    place.marker_lat = None
                    place.marker_lng = None
                    if 0 < place.countLog :
                        place.activity = place.activityLog
                        place.moreinfo = place.moreinfoLog
                        place.color = place.colorLog
                        place.category = place.categoryLog
                    else:
                        place.people = ""
                        place.contact = ""
                        place.activity = ""
                        place.moreinfo = ""
                        place.prevgroup = ""
                        place.nextgroup = ""
                        place.acrossgroup = ""
                        place.pintext = ""
                    place.mapdefined = True
                    place.put()
                    pin = Pin(key_name=place_id)
                    pin.name = place_id
                    pin.put()
                    template_values = dict(place_id=place.key(), place=place.place, 
                        people=place.people, center_lat=place.center_lat, 
                        center_lng=place.center_lng, map_zoom=place.zoom,
                        marker_lat=place.marker_lat, marker_lng=place.marker_lng, 
                        contact=place.contact, moreinfo=place.moreinfo,
                        category=place.category, color=place.color,
                        prevgroup=place.prevgroup, nextgroup=place.nextgroup,
                        acrossgroup=place.acrossgroup, pintext=place.pintext,
                        mapdefined=place.mapdefined,
                        countLog=place.countLog,
                        activity=place.activity, user=place.user)
                    path = os.path.join(os.path.dirname(__file__), 'add_map.html')
                    self.response.out.write(template.render(path, template_values))
                else: #send nonuser back to choose.html
                    url = users.create_login_url(self.request.uri)
                    url_linktext = 'Signin'
                    url_linktextmore = ' if you will be creating a map for your group. You will be returned to this page after you signin. <b> You may have mispelled your group. </b>'
                    template_values = {
                        'url': url,
                        'url_linktext': url_linktext,
                        'url_linktextmore': url_linktextmore,
                        'interstateList': interstateList,
                        }
                    path = os.path.join(os.path.dirname(__file__), 'choose_place.html')
                    self.response.out.write(template.render(path, template_values))

class OwnerMap(webapp.RequestHandler):
    def get(self):
        place_id = self.request.get("place", None)
        if place_id is None:
            ####'choose_place' on next line does not seem to matter
            path = os.path.join(os.path.dirname(__file__), 'choose_place.html')
            template_values = dict()
            self.response.out.write(template.render(path, template_values))
        else:
            ####go to map.html
            ####because choose_place.html has produced a desired place name
            key = db.Key.from_path("Group", place_id)
            place = Group.get(key)
            if place : 
                user = users.get_current_user()
                if user and user == place.user: #send user to mapowner.html
                    template_values = dict(place_id=place.key(), place=place.place, 
                         people=place.people, center_lat=place.center_lat, 
                         center_lng=place.center_lng, map_zoom=place.zoom,
                         marker_lat=place.marker_lat, marker_lng=place.marker_lng, 
                         contact=place.contact, moreinfo=place.moreinfo,
                         category=place.category, color=place.color,
                         mapdefined=place.mapdefined, pintext=place.pintext,
                         countLog=place.countLog,
                         activity=place.activity, user=place.user)
                    path = os.path.join(os.path.dirname(__file__), 'mapowner.html')
                else:                           #send to choose_place.html
                    template_values = dict()
                    path = os.path.join(os.path.dirname(__file__), 'choose_place')
                self.response.out.write(template.render(path, template_values))

class LogMainPage(webapp.RequestHandler):
    def get(self):
        place_id = self.request.get("place", None)
        user = users.get_current_user()
        groups = db.GqlQuery("SELECT * FROM Group WHERE acrossgroup != '' ORDER BY acrossgroup , countLog DESC  LIMIT 500") 
        pattern = "I\d\d*"
        compiledPattern = re.compile(pattern)

        interstates = {}
        for group in groups:
            index = compiledPattern.search(group.place).group()
            interstates[index] = group.place

        interstateList = []
        for interstate in interstates:
            logging.info("place %s " % interstates[interstate])
            interstateList.append(interstates[interstate])

        if place_id is None: #no place has been set by the user
            path = os.path.join(os.path.dirname(__file__), 'choose_place.html')
            if user: #offer user or nonuser options back at choose.html
                url = users.create_logout_url(self.request.uri)
                url_linktext = 'Signout'
                url_linktextmore = ' if you wish. You will be returned to this page after you signout.'
            else:
                url = users.create_login_url(self.request.uri)
                url_linktext = 'Signin'
                url_linktextmore = ' if you will be creating a map for your group. You will be returned to this page after you signin.'
            template_values = {
                'url': url,
                'url_linktext': url_linktext,
                'url_linktextmore': url_linktextmore,
                'interstateList': interstateList,
                }
            self.response.out.write(template.render(path, template_values))
        else: #some place has been set by the person (may be user)
            #so pull up information on the place set by the person
            key = db.Key.from_path("Group", place_id)
            place = Group.get(key)
            #determine if place exists already
            #because choose_place.html has produced a desired place name
            #or because user has supplied a place name with ?...
            if place: #person's place DOES exist already
                chtml = captcha.displayhtml(
                  public_key = "6Ld79wQAAAAAAKZvFiUW2J7WCFX0Iv_-fveFNOb5",
                  use_ssl = False,
                  error = None)
                if 0 < place.countLog: #person's place exists as a log
                    if user and user == place.user: #user is owner and may revise the existing log
                        template_values = dict(place_id=place.key(), place=place.place, 
                            people=place.people, 
                            contact=place.contact, moreinfo=place.moreinfoLog,
                            category=place.categoryLog, color=place.colorLog,
                            prevgroup=place.prevgroup, nextgroup=place.nextgroup,
                            acrossgroup=place.acrossgroup, pintext=place.pintext,
                            mapdefined=place.mapdefined,
                            countLog=place.countLog, captchahtml = chtml,
                            activity=place.activityLog, user=place.user)
                        path = os.path.join(os.path.dirname(__file__), 'add_log.html')
                        self.response.out.write(template.render(path, template_values))
                    else: #is not a user so may only view the existing log
                        self.redirect("/comment?place=%s" % place.place)
                else: #person's place does NOT exist as a log
                    if user: #user needs to create the log but map exists
                        if place.mapdefined :
                            place.activityLog = place.activity
                            place.moreinfoLog = place.moreinfo
                            place.colorLog = place.color
                            place.categoryLog = place.category
                            place.prevgroupLog = place.prevgroup
                            place.nextgroupLog = place.nextgroup
                            place.acrossgroupLog = place.acrossgroup
                        else:
                            place.people = ""
                            place.contact = ""
                            place.activity = ""
                            place.moreinfo = ""
                            place.prevgroup = ""
                            place.nextgroup = ""
                            place.acrossgroup = ""
                            place.pintext = ""
                        place.countLog += 1
                        place.put()
                        template_values = dict(place_id=place.key(), place=place.place, 
                            people=place.people, 
                            contact=place.contact, moreinfo=place.moreinfoLog,
                            category=place.categoryLog, color=place.colorLog,
                            prevgroup=place.prevgroup, nextgroup=place.nextgroup,
                            acrossgroup=place.acrossgroup, pintext=place.pintext,
                            mapdefined=place.mapdefined,
                            countLog=place.countLog,
                            activity=place.activityLog, user=place.user)
                        path = os.path.join(os.path.dirname(__file__), 'add_log.html')
                        self.response.out.write(template.render(path, template_values))
                    else: #send person to the existing map
                        self.redirect("/?place=%s" % place.place)
            else: #person's place does NOT exist in datastore
                if user: #user needs to create the map
                    place= Group(key_name=place_id)
                    place.place = place_id
                    place.user = user
                    if place.mapdefined :
                        place.activityLog = place.activity
                        place.moreinfoLog = place.moreinfo
                        place.colorLog = place.color
                        place.categoryLog = place.category
                        place.prevgroupLog = place.prevgroup
                        place.nextgroupLog = place.nextgroup
                        place.acrossgroupLog = place.acrossgroup
                        #place.pintextLog = place.pintext
                    else:
                        place.people = ""
                        place.contact = ""
                        place.activity = ""
                        place.moreinfo = ""
                        place.prevgroup = ""
                        place.nextgroup = ""
                        place.acrossgroup = ""
                        place.pintext = ""
                    place.countLog += 1
                    place.put()
                    template_values = dict(place_id=place.key(), place=place.place, 
                         people=place.people, 
                         contact=place.contact, moreinfo=place.moreinfoLog,
                         category=place.categoryLog, color=place.colorLog,
                         prevgroup=place.prevgroup, nextgroup=place.nextgroup,
                         acrossgroup=place.acrossgroup, pintext=place.pintext,
                         mapdefined=place.mapdefined,
                         countLog=place.countLog,
                         activity=place.activityLog, user=place.user)
                    path = os.path.join(os.path.dirname(__file__), 'add_log.html')
                    self.response.out.write(template.render(path, template_values))
                else: #send nonuser back to choose.html
                    if user: #offer user or nonuser options back at choose.html
                        url = users.create_logout_url(self.request.uri)
                        url_linktext = 'Signout'
                        url_linktextmore = ' if you wish. You will be returned to this page after you signout.'
                    else:
                        url = users.create_login_url(self.request.uri)
                        url_linktext = 'Signin'
                        url_linktextmore = ' if you will be creating a map for your group. You will be returned to this page after you signin. <b> You may have mispelled your group. </b>'
                    template_values = {
                        'url': url,
                        'url_linktext': url_linktext,
                        'url_linktextmore': url_linktextmore,
                        'interstateList': interstateList,
                        }
                    path = os.path.join(os.path.dirname(__file__), 'choose_place.html')
                    self.response.out.write(template.render(path, template_values))

class OwnerLog(webapp.RequestHandler):
    def get(self):
        place_id = self.request.get("place", None)
        if place_id is None:
            ####'choose_place' on next line does not seem to matter
            path = os.path.join(os.path.dirname(__file__), 'choose_place.html')
            template_values = dict()
            self.response.out.write(template.render(path, template_values))
        else:
            ####go to log.html
            ####because choose_place.html has produced a desired place name
            key = db.Key.from_path("Group", place_id)
            place = Group.get(key)
            if place : 
                user = users.get_current_user()
                if user and user == place.user: #send user to logowner.html
                    bookmark = self.request.get("bookmark")
                    next = None
                    #image = db.get(self.request.get("img"))
                    if bookmark:
                        query = Log.gql('WHERE when <= :bookmark AND deleteRequested = True AND ANCESTOR IS :place ORDER BY when DESC', 
                        bookmark=bookmark, place=place)      
                        comments = query.fetch(PAGESIZE+1)      
                    else:
                        comments = Log.gql('WHERE deleteRequested = True AND ANCESTOR IS :place ORDER BY when DESC',
                                        place=place).fetch(PAGESIZE+1)
                    if len(comments) == PAGESIZE+1:
                        next = comments[-1].when
                        comments = comments[:PAGESIZE]
  
                    template_values = dict(place_id=place.key(), place=place.place, 
                         next=next, comments=comments,
                         people=place.people, 
                         contact=place.contact, moreinfo=place.moreinfoLog,
                         categories=place.categoryLog, colors=place.colorLog,
                         prevgroup=place.prevgroup, nextgroup=place.nextgroup,
                         acrossgroup=place.acrossgroup, pintext=place.pintext,
                         mapdefined=place.mapdefined,
                         countLog=place.countLog,
                         activity=place.activityLog, user=place.user)
                    path = os.path.join(os.path.dirname(__file__), 'logowner.html')
                else:                           #send to choose_place.html
                    template_values = dict()
                    path = os.path.join(os.path.dirname(__file__), 'choose_place')
                self.response.out.write(template.render(path, template_values))

    def post(self):
      place_id = self.request.get("place")
      key = db.Key.from_path("Group", place_id)
      place = Group.get(key)
      if self.request.get('undeleteID'): 
          comment = Log.get(self.request.get('undeleteID'))
          comment.deleteRequested = False
          comment.put()
          self.response.out.write("comment undeleted")
      self.redirect('/logowner?place=%s&people=%s&activity=%s' %
                      (place_id,place.people,place.activity))


def whenfromcreated(created):
    return created.isoformat()[0:19] 
    
####This handler was made possible by an Article by Joe Gregorio
####  and by his code at the following link
####  http://code.google.com/p/google-app-engine-samples/source/browse/#svn/trunk/paging
class DetailsLog(webapp.RequestHandler):
  def get(self):
    place_id = self.request.get("place")
    key = db.Key.from_path("Group", place_id)
    place = Group.get(key)
    people = place.people
    mapdefined = place.mapdefined
    moreinfoLog = place.moreinfoLog
    prevgroup = place.prevgroup
    nextgroup = place.nextgroup
    acrossgroup = place.acrossgroup
    activity = place.activityLog
    categories = place.categoryLog
    colors = place.colorLog
    bookmark = self.request.get("bookmark")
    next = None
    #image = db.get(self.request.get("img"))
    logging.info("people: %s " % (people))
    if bookmark:
      #query = Log.gql('WHERE when <= :bookmark AND ANCESTOR IS :place ORDER BY when DESC', 
      query = Log.gql('WHERE when <= :bookmark AND deleteRequested = False AND ANCESTOR IS :place ORDER BY when DESC', 
        bookmark=bookmark, place=place)      
      comments = query.fetch(PAGESIZE+1)      
    else:
      #comments = Log.gql('WHERE ANCESTOR IS :place ORDER BY when DESC',
      comments = Log.gql('WHERE deleteRequested = False AND ANCESTOR IS :place ORDER BY when DESC',
                         place=place).fetch(PAGESIZE+1)
    if len(comments) == PAGESIZE+1:
      next = comments[-1].when
      comments = comments[:PAGESIZE]
  
    chtml = captcha.displayhtml(
      public_key = "6Ld79wQAAAAAAKZvFiUW2J7WCFX0Iv_-fveFNOb5",
      use_ssl = False,
      error = None)

    
    template_values = {'next': next, 'comments': comments, 'moreinfoLog': moreinfoLog, 'mapdefined': mapdefined, 'prevgroup': prevgroup, 'nextgroup': nextgroup, 'acrossgroup': acrossgroup, 'people': people, 'activity': activity, 'place': place_id, 'colors': colors, 'categories': categories, 'captchahtml': chtml}    
    #template_values = {'next': next, 'captchahtml': chtml}   # to initialize use this one 
    template_file = os.path.join(os.path.dirname(__file__), 'log.html')
    self.response.out.write(template.render(template_file, template_values))

  def post(self):
    logging.info("challenge " )
    challenge = self.request.get('recaptcha_challenge_field')
    response  = self.request.get('recaptcha_response_field')
    remoteip  = self.request.remote_addr 

    cResponse = captcha.submit(
                challenge,
                response,
      "privatekey",
                remoteip)
    if cResponse.is_valid:
        place_id = self.request.get("place")
        key = db.Key.from_path("Group", place_id)
        place = Group.get(key)
        if self.request.get('deleteID'): 
            comment = Log.get(self.request.get('deleteID'))
            comment.deleteRequested = True
            comment.put()
            #db.delete(comment)
            self.response.out.write("comment deleted")
        if '' != self.request.get('comment'): 
            now = datetime.datetime.now()
            when = whenfromcreated(now)
            category = int(self.request.get('category')) 
            scategory = place.categoryLog[category]
            scolor = place.colorLog[category]
            logging.info("category: %s " % (category))
            image = ''
            s = Log(
              parent = place,
              ID = place.countLog,
              comment = self.request.get('comment'), 
              category = int(self.request.get('category')), 
              scategory = scategory, 
              scolor = scolor, 
              name = self.request.get('name'), 
              pinlabel = self.request.get('pinlabel'),
              when = when,
              created = now) 
            if '' != self.request.get('img'): 
                s.image = images.resize(self.request.get("img"), 480, 480)
                s.imageindex += 1
            new_id = s.put()
            place.countLog +=  1
            place.put()
            self.response.out.write(new_id)
        self.redirect('/comment?place=%s&people=%s&activity=%s' %
                      (place_id,place.people,place.activity))
    else:
        chtml = captcha.displayhtml(
          public_key = "6Ld79wQAAAAAAKZvFiUW2J7WCFX0Iv_-fveFNOb5",
          use_ssl = False,
          error = cResponse.error_code)        
        self.response.out.write("An error occurred with the reCaptcha. Try refreshing (reloading) this page.")
        #self.redirect('/comment')        
    
    
class Details(webapp.RequestHandler):
    def get(self):
        action = self.request.get("Action", "read")
        place_id = self.request.get("place")
        key = db.Key.from_path("Group", place_id)
        place = Group.get(key)
        
        if action == "read":
            #pins = db.GqlQuery("SELECT * FROM Pin where  ancestor is :group LIMIT 100", group=place)
            pins = db.GqlQuery("SELECT * FROM Pin where deleteRequested = False AND ancestor is :group LIMIT 100", group=place)
            cnt = 1
            pinage = 0
            time =  datetime.datetime.now()
            ord = time.toordinal()
            for pin in pins:
                pintime= pin.date
                pinord = pintime.toordinal()
                pinage = ord - pinord
                sPinage = "%s" % pinage
                self.response.out.write("\t".join( (str(pin.key()),
                  pin.date.strftime('%a %m %d %Y %H%M'), str(pin.lat),
                  str(pin.lng), pin.name, str(pin.category), pin.label,
                  sPinage,) ) )
                cnt += 1
                self.response.out.write("\n")
        elif action == "add":
            pin = Pin(parent=place)
            pin.name = self.request.get('details')
            pin.lat = float(self.request.get('lat'))
            pin.lng = float(self.request.get('lng'))
            pin.category = int(self.request.get('category'))
            pin.label = self.request.get('label')
            new_id = pin.put()
            self.response.out.write(new_id)
        elif action == "del":
            pin = Pin.get(self.request.get('ID'))
            pin.deleteRequested = True
            pin.put()
            #db.delete(pin)
            self.response.out.write("pin deleted")
            
class AddMap(webapp.RequestHandler):
    #creates group 
    def get(self):
        place_id = self.request.get('place')
        key = db.Key.from_path("Group", place_id)
        group = Group.get(key)
        group.place = place_id
        group.center_lat = float(self.request.get('center_lat'))
        group.center_lng = float(self.request.get('center_lng'))
        group.zoom = int(self.request.get('zoom'))
        group.people = self.request.get('people')
        group.contact = self.request.get('contact')
        group.activity = self.request.get('activity')
        group.moreinfo = self.request.get('moreinfo')
        group.prevgroup = self.request.get('prevgroup')
        group.nextgroup = self.request.get('nextgroup')
        group.acrossgroup = self.request.get('acrossgroup')
        group.pintext = self.request.get('pintext')
        color = self.request.get('colors')
        group.color = color.split()
        category = self.request.get('categories')
        group.category = category.split()
        group.marker_lat = float(self.request.get('marker_lat'))
        group.marker_lng = float(self.request.get('marker_lng'))
        #this pin should NOT have a parent so it is not
        #included in the many ancestor pins
        key = db.Key.from_path("Pin", place_id)
        pin = Pin.get(key)
        pin.name = place_id
        pin.lat = float(self.request.get('marker_lat'))
        pin.lng = float(self.request.get('marker_lng'))
        pin.put()
        group.mapdefined = True
        group.put()
        self.redirect("/?place=%s" % place_id)
            
class AddLog(webapp.RequestHandler):
    #creates group 
    def get(self):
        place_id = self.request.get('place')
        key = db.Key.from_path("Group", place_id)
        group = Group.get(key)
        group.place = place_id
        group.people = self.request.get('people')
        group.contact = self.request.get('contact')
        group.activityLog = self.request.get('activityLog')
        group.moreinfoLog = self.request.get('moreinfoLog')
        group.prevgroupLog = self.request.get('prevgroupLog')
        group.nextgroupLog = self.request.get('nextgroupLog')
        group.acrossgroupLog = self.request.get('acrossgroupLog')
        #group.pintextLog = self.request.get('pintextLog')
        color = self.request.get('colors')
        group.colorLog = color.split()
        category = self.request.get('categories')
        group.categoryLog = category.split()
        #this pin should NOT have a parent so it is not
        #included in the many ancestor pins
        group.put()
        self.redirect("/mainlog?place=%s" % place_id)
            
class nextMainPage(webapp.RequestHandler):
    def get(self):
        place_id = self.request.get("place", None)
        nextplace_id = self.request.get("nextplace", None)
        prevplace_id = self.request.get("prevplace", None)
        user = users.get_current_user()
        if place_id is None: #user has not been to choose_place.html
            path = os.path.join(os.path.dirname(__file__), 'choose_placenextprev.html')
            if user: #offer user or nonuser options back at choose.html
                url = users.create_logout_url(self.request.uri)
                url_linktext = 'Signout'
                url_linktextmore = ' if you wish. You will be returned to this page after you signout. '
            else:
                url = users.create_login_url(self.request.uri)
                url_linktext = 'Signin'
                url_linktextmore = ' if you will be creating a map for your group. You will be returned to this page after you signin.'
            template_values = {
                'url': url,
                'url_linktext': url_linktext,
                'url_linktextmore': url_linktextmore,
                }
            self.response.out.write(template.render(path, template_values))
        else: # person has supplied a place already
            if place_id == '': #no place has been set by the user
                path = os.path.join(os.path.dirname(__file__), 'choose_placenextprev.html')
                if user: #offer user or nonuser options back at choose.html
                    url = users.create_logout_url(self.request.uri)
                    url_linktext = 'Signout'
                    url_linktextmore = ' if you wish. You will be returned to this page after you signout. <b>Otherwise, supply a place name. </b>'
                else:
                    url = users.create_login_url(self.request.uri)
                    url_linktext = 'Signin'
                    url_linktextmore = ' if you will be creating a map for your group. You will be returned to this page after you signin.'
                template_values = {
                    'url': url,
                    'url_linktext': url_linktext,
                    'url_linktextmore': url_linktextmore,
                    }
                self.response.out.write(template.render(path, template_values))
            else: #some place has been set
                if prevplace_id == '' and nextplace_id == '': #no nextprev place has been set by the user
                    path = os.path.join(os.path.dirname(__file__), 'choose_placenextprev.html')
                    if user: #offer user or nonuser options back at choose.html
                        url = users.create_logout_url(self.request.uri)
                        url_linktext = 'Signout'
                        url_linktextmore = ' if you wish. You will be returned to this page after you signout. <b>Ortherwise, supply a next or previous name, too. </b>'
                    else:
                        url = users.create_login_url(self.request.uri)
                        url_linktext = 'Signin'
                        url_linktextmore = ' if you will be creating a map for your group. You will be returned to this page after you signin.'
                    template_values = {
                        'url': url,
                        'url_linktext': url_linktext,
                        'url_linktextmore': url_linktextmore,
                        }
                    self.response.out.write(template.render(path, template_values))
                else: #some place has been set by the person (may be user)
                    #so pull up information on the place set by the person
                    key = db.Key.from_path("Group", place_id)
                    place = Group.get(key)
                    #determine if place exists already
                    #because choose_placenextprev.html has produced a place name
                    #or because user has supplied a place name with ?...
                    if not place: #person's place does NOT exist already
                        path = os.path.join(os.path.dirname(__file__), 'choose_placenextprev.html')
                        if user: #offer user or nonuser options back at choose_placenextprev.html
                            url = users.create_logout_url(self.request.uri)
                            url_linktext = 'Signout'
                            url_linktextmore = ' if you wish. You will be returned to this page after you signout. <b>The current place must already exist. </b>'
                        else:
                            url = users.create_login_url(self.request.uri)
                            url_linktext = 'Signin'
                            url_linktextmore = ' if you will be creating a map for your group. You will be returned to this page after you signin.'
                        template_values = {
                            'url': url,
                            'url_linktext': url_linktext,
                            'url_linktextmore': url_linktextmore,
                            }
                        self.response.out.write(template.render(path, template_values))
                        
                    else: #next or prev place has been set
    	                if prevplace_id == '': #next place has been set by the user
        	                template_values = dict(place_id=place.key(), prevgroup=place.place, 
        	                    people=place.people, center_lat=place.center_lat, 
        	                    center_lng=place.center_lng, map_zoom=place.zoom,
        	                    marker_lat=place.marker_lat, marker_lng=place.marker_lng, 
        	                    contact=place.contact, moreinfo=place.moreinfo,
        	                    activityLog=place.activityLog, moreinfoLog=place.moreinfoLog,
        	                    nextgroup=place.nextgroup, place=nextplace_id,
        	                    acrossgroup=place.nextgroup, pintext=place.pintext,
        	                    category=place.category, color=place.color,
        	                    categoryLog=place.categoryLog, colorLog=place.colorLog,
        	                    mapdefined=place.mapdefined, origplace=place_id,
        	                    orignext=nextplace_id, origprev=prevplace_id,
        	                    countLog=place.countLog,
        	                    activity=place.activity)
        	                if place.mapdefined: #person's place exists as a map
        	                    if user: #user may revise the existing map
    	                                path = os.path.join(os.path.dirname(__file__), 'add_nextmap.html')
    	                                self.response.out.write(template.render(path, template_values))
                                    else:
                                        path = os.path.join(os.path.dirname(__file__), 'choose_placenextprev.html')
                                        url = users.create_login_url(self.request.uri)
                                        url_linktext = 'Signin'
                                        url_linktextmore = ' if you will be creating a map for your group. You will be returned to this page after you signin.'
                                        template_values = {
                                            'url': url,
                                            'url_linktext': url_linktext,
                                            'url_linktextmore': url_linktextmore,
                                            }
                                        self.response.out.write(template.render(path, template_values))
    	                        else: #no original map defined, send back to choose
    	                            path = os.path.join(os.path.dirname(__file__), 'choose_placenextprev.html')
    	                            if user: #offer user or nonuser options back at choose.html
    	                                url = users.create_logout_url(self.request.uri)
    	                                url_linktext = 'Signout'
    	                                url_linktextmore = ' if you wish. You will be returned to this page after you signout.  <b>Otherwise, supply the name of an existing Next place. </b>'
    	                            else:
    	                                url = users.create_login_url(self.request.uri)
    	                                url_linktext = 'Signin'
    	                                url_linktextmore = ' if you will be creating a map for your group. You will be returned to this page after you signin.'
    	                            template_values = {
    	                                'url': url,
    	                                'url_linktext': url_linktext,
    	                                'url_linktextmore': url_linktextmore,
    	                                }
    	                            self.response.out.write(template.render(path, template_values))
    	                else: #prev place has been set by the user
    	                    template_values = dict(place_id=place.key(), nextgroup=place.place, 
    	                        people=place.people, center_lat=place.center_lat, 
    	                        center_lng=place.center_lng, map_zoom=place.zoom,
    	                        marker_lat=place.marker_lat, marker_lng=place.marker_lng, 
    	                        contact=place.contact, moreinfo=place.moreinfo,
        	                activityLog=place.activityLog, moreinfoLog=place.moreinfoLog,
    	                        prevgroup=place.prevgroup, place=prevplace_id,
    	                        acrossgroup=place.prevgroup, pintext=place.pintext,
    	                        category=place.category, color=place.color,
        	                categoryLog=place.categoryLog, colorLog=place.colorLog,
    	                        mapdefined=place.mapdefined,  origplace=place_id,
        	                orignext=nextplace_id, origprev=prevplace_id,
    	                        countLog=place.countLog,
    	                        activity=place.activity)
    	                    if place.mapdefined: #person's place exists as a map
    	                        if user: #user may revise the existing map
    	                            path = os.path.join(os.path.dirname(__file__), 'add_nextmap.html')
    	                            self.response.out.write(template.render(path, template_values))
                                else:
                                    path = os.path.join(os.path.dirname(__file__), 'choose_placenextprev.html')
                                    url = users.create_login_url(self.request.uri)
                                    url_linktext = 'Signin'
                                    url_linktextmore = ' if you will be creating a map for your group. You will be returned to this page after you signin.'
                                    template_values = {
                                        'url': url,
                                        'url_linktext': url_linktext,
                                        'url_linktextmore': url_linktextmore,
                                        }
                                    self.response.out.write(template.render(path, template_values))
    	                    else: #no original map defined, send back to choose
    	                        path = os.path.join(os.path.dirname(__file__), 'choose_placenextprev.html')
    	                        if user: #offer user or nonuser options back at choose.html
    	                            url = users.create_logout_url(self.request.uri)
    	                            url_linktext = 'Signout'
    	                            url_linktextmore = ' if you wish. You will be returned to this page after you signout. <b>Otherwise, supply the name of an existing Prev place. </b>'
    	                        else:
    	                            url = users.create_login_url(self.request.uri)
    	                            url_linktext = 'Signin'
    	                            url_linktextmore = ' if you will be creating a map for your group. You will be returned to this page after you signin.'
    	                        template_values = {
    	                            'url': url,
    	                            'url_linktext': url_linktext,
    	                            'url_linktextmore': url_linktextmore,
    	                            }
    	                        self.response.out.write(template.render(path, template_values))
                    

class AddMapnext(webapp.RequestHandler):
    #creates group 
    def get(self):
        place_id = self.request.get('place')
        origplace_id = self.request.get('origplace')
        group= Group(key_name=place_id)
        group.place = place_id
        logging.info("place_id: %s " % (place_id))
        user = users.get_current_user()
        group.user = user
        group.countLog += 1
        group.center_lat = float(self.request.get('center_lat'))
        group.center_lng = float(self.request.get('center_lng'))
        group.zoom = int(self.request.get('zoom'))
        group.people = self.request.get('people')
        group.contact = self.request.get('contact')
        group.activity = self.request.get('activity')
        group.moreinfo = self.request.get('moreinfo')
        group.activityLog = self.request.get('activityLog')
        group.moreinfoLog = self.request.get('moreinfoLog')
        group.prevgroup = self.request.get('prevgroup')
        group.nextgroup = self.request.get('nextgroup')
        group.acrossgroup = self.request.get('acrossgroup')
        group.pintext = self.request.get('pintext')
        color = self.request.get('colors')
        group.color = color.split()
        category = self.request.get('categories')
        group.category = category.split()
        colorLog = self.request.get('colorsLog')
        group.colorLog = colorLog.split()
        categoryLog = self.request.get('categoriesLog')
        group.categoryLog = categoryLog.split()
        group.marker_lat = float(self.request.get('marker_lat'))
        group.marker_lng = float(self.request.get('marker_lng'))
        pin = Pin(key_name=place_id)
        pin.name = place_id
        pin.lat = float(self.request.get('marker_lat'))
        pin.lng = float(self.request.get('marker_lng'))
        pin.put()
        group.mapdefined = True
        group.put()
        self.redirect('/mainaddnext')

class Image (webapp.RequestHandler):
  def get(self):
    log = db.get(self.request.get("img_id"))
    if log.image:
      self.response.headers['Content-Type'] = "image/png"
      self.response.out.write(log.image)
    else:
      self.response.out.write("No image")

class UpdateDS(webapp.RequestHandler):
# Request handler for the URL /update_datastore
    def get(self):
      date = self.request.get('date', None)
      if date is None:
        # First request, just get the first date out of the datastore.
        #pin = Pin.gql('ORDER BY date DESC').get()
        pin = Pin.gql('ORDER BY date').get()
        #date = pin.date
        date = pin.date.strftime('%Y-%m-%d %H:%M:%S')

      date = datetime.datetime.strptime(date,'%Y-%m-%d %H:%M:%S')
      #q = Pin.gql('WHERE date <= :1 ORDER BY date DESC', date)
      q = Pin.gql('WHERE date >= :1 ORDER BY date', date)
      pins = q.fetch(limit=2)
      current_pin = pins[0]
      if len(pins) == 2:
        #next_date = pins[1].date
        next_date = pins[1].date.strftime('%Y-%m-%d %H:%M:%S')
        next_url = '/update_datastore?date=%s' % urllib.quote(next_date)
      else:
        next_date = 'FINISHED'
        next_url = '/'  # Finished processing, go back to main page.
      # In this example, the default values of 0 for num_votes and avg_rating are
      # acceptable, so we don't need to do anything other than call put().
      current_pin.put()

      context = {
        'current_date': date,
        'next_date': next_date,
        'next_url': next_url,
      }
      self.response.out.write(template.render('update_datastore.html', context))
  
class UpdateLogDS(webapp.RequestHandler):
# Request handler for the URL /update_datastore
    def get(self):
      created = self.request.get('created', None)
      if created is None:
        # First request, just get the first created out of the datastore.
        #pin = Log.gql('ORDER BY created DESC').get()
        pin = Log.gql('ORDER BY created').get()
        #created = pin.created
        created = pin.created.strftime('%Y-%m-%d %H:%M:%S')

      created = datetime.datetime.strptime(created,'%Y-%m-%d %H:%M:%S')
      #q = Log.gql('WHERE created <= :1 ORDER BY created DESC', created)
      q = Log.gql('WHERE created >= :1 ORDER BY created', created)
      pins = q.fetch(limit=2)
      current_pin = pins[0]
      if len(pins) == 2:
        #next_created = pins[1].created
        next_created = pins[1].created.strftime('%Y-%m-%d %H:%M:%S')
        next_url = '/updateLog_datastore?created=%s' % urllib.quote(next_created)
      else:
        next_created = 'FINISHED'
        next_url = '/'  # Finished processing, go back to main page.
      # In this example, the default values of 0 for num_votes and avg_rating are
      # acceptable, so we don't need to do anything other than call put().
      current_pin.put()

      context = {
        'current_created': created,
        'next_created': next_created,
        'next_url': next_url,
      }
      self.response.out.write(template.render('updateLog_datastore.html', context))
  
        

            
application = webapp.WSGIApplication(
                                     [('/', MainPage),
                                      ('/mainlog', LogMainPage),
                                      ('/details.txt', Details),
                                      ('/mapowner', OwnerMap),
                                      ('/logowner', OwnerLog),
                                      ('/mainaddnext', nextMainPage),
                                      ('/add_nextmap', AddMapnext),
                                      ('/add_map', AddMap),
                                      ('/add_log', AddLog),
                                      ('/img', Image),
                                      ('/update_datastore', UpdateDS),
                                      ('/updateLog_datastore', UpdateLogDS),
                                      ('/comment', DetailsLog)],
                                     debug=True)

                    
def profile_main():
 # This is the main function for profiling 
 # We've renamed our original main() above to real_main()
 import cProfile, pstats
 prof = cProfile.Profile()
 prof = prof.runctx("real_main()", globals(), locals())
 print "<pre>"
 stats = pstats.Stats(prof)
 stats.sort_stats("time")  # Or cumulative
 stats.print_stats(80)  # 80 = how many to print
 # The rest is optional.
 # stats.print_callees()
 # stats.print_callers()
 print "</pre>"

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
